<template>
  <div v-if="visible" class="modal-overlay" @click="closeModal">
    <div class="modal" @click.stop>
      <div class="modal-header">
        <div class="modal-title">
          <h2>项目趋势分析</h2>
          <p>{{ project?.project_code || 'N/A' }} - 过去15天数据走势</p>
        </div>
        <button class="close-btn" @click="closeModal">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <line x1="18" y1="6" x2="6" y2="18"></line>
            <line x1="6" y1="6" x2="18" y2="18"></line>
          </svg>
        </button>
      </div>

      <div class="modal-body">
        <div class="tabs-container">
          <div class="tabs">
            <button v-for="(item, index) in trendData" :key="item.id" class="tab"
              :class="{ active: currentItemIndex === index }" @click="switchTab(index)">
              {{ item.name }}
              <span class="tab-badge">{{ item.current }}/{{ item.target }}</span>
            </button>
          </div>
        </div>

        <div class="chart-container">
          <!-- Loading state -->
          <div v-if="loading" class="loading-container">
            <div class="loading-spinner"></div>
            <p>正在加载趋势数据...</p>
          </div>

          <!-- Error state -->
          <div v-else-if="error" class="error-container">
            <div class="error-icon">⚠️</div>
            <p>{{ error }}</p>
            <button @click="fetchTimelineData" class="retry-btn">重试</button>
          </div>

          <!-- No data state -->
          <div v-else-if="trendData.length === 0" class="no-data-container">
            <div class="no-data-icon">📊</div>
            <p>暂无趋势数据</p>
          </div>

          <!-- Chart content -->
          <template v-else>
            <div class="chart-header">
              <div class="chart-info">
                <h3>{{ currentItem?.name || '暂无数据' }}</h3>
                <p>过去15天的完成数量趋势 - 目标: {{ currentItem?.target || 0 }}条</p>
              </div>
              <div class="chart-actions">
                <button class="export-btn" @click="exportCurrentData"
                  :disabled="exportLoading || !currentItem || progress === 0" :class="{ loading: exportLoading }">
                  <div v-if="exportLoading" class="export-loading">
                    <div class="export-spinner"></div>
                    <span>导出中...</span>
                  </div>
                  <div v-else class="export-content">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                      <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
                      <polyline points="7,10 12,15 17,10"></polyline>
                      <line x1="12" y1="15" x2="12" y2="3"></line>
                    </svg>
                    <span>导出Excel</span>
                  </div>
                </button>
              </div>
              <div class="chart-stats">
                <div class="stat-item">
                  <div class="stat-value">{{ currentItem?.current || 0 }}</div>
                  <div class="stat-label">当前完成数量</div>
                  <div class="stat-change" :class="weeklyChange >= 0 ? 'positive' : 'negative'">
                    {{ weeklyChange >= 0 ? '+' : '' }}{{ weeklyChange }} 本周
                  </div>
                </div>
                <div class="stat-item">
                  <div class="stat-value">{{ progress }}%</div>
                  <div class="stat-label">完成率</div>
                </div>
                <div class="stat-item">
                  <div class="stat-value">{{ remaining }}</div>
                  <div class="stat-label">剩余目标</div>
                </div>
              </div>
            </div>

            <div class="chart-wrapper">
              <div class="chart">
                <svg class="chart-canvas" viewBox="0 0 800 300" v-if="currentItem">
                  <defs>
                    <linearGradient id="gradient" x1="0%" y1="0%" x2="0%" y2="100%">
                      <stop offset="0%" style="stop-color:#6366f1;stop-opacity:0.3" />
                      <stop offset="100%" style="stop-color:#6366f1;stop-opacity:0" />
                    </linearGradient>
                  </defs>

                  <!-- Grid lines -->
                  <line v-for="i in 5" :key="`grid-${i}`" x1="60" :y1="60 + (i - 1) * 48" x2="740"
                    :y2="60 + (i - 1) * 48" stroke="#e5e7eb" stroke-width="1" opacity="0.5" />

                  <!-- Target line -->
                  <path v-if="currentItem.target > 0"
                    :d="`M 60 ${260 - (currentItem.target / maxValue) * 200} L 740 ${260 - (currentItem.target / maxValue) * 200}`"
                    stroke="#f59e0b" stroke-width="2" stroke-dasharray="5,5" opacity="0.7" />

                  <!-- Target label -->
                  <text v-if="currentItem.target > 0" x="750" :y="265 - (currentItem.target / maxValue) * 200"
                    font-size="12" fill="#f59e0b" text-anchor="start">
                    目标: {{ currentItem.target }}
                  </text>

                  <!-- Actual progress line -->
                  <path :d="progressPath" class="line-path" />

                  <!-- Area under curve -->
                  <path :d="areaPath" class="line-area" />

                  <!-- Data points -->
                  <circle v-for="(point, i) in currentItem.dailyData" :key="`point-${i}`"
                    :cx="60 + (i * 680 / (currentItem.dailyData.length - 1))" :cy="260 - (point.value / maxValue) * 200"
                    class="line-point">
                    <title>{{ point.date }}: {{ point.value }}</title>
                  </circle>

                  <!-- Y-axis labels -->
                  <text v-for="i in 5" :key="`y-label-${i}`" x="50" :y="265 - (i - 1) * 48" text-anchor="end"
                    font-size="12" fill="#6b7280">
                    {{ Math.round((maxValue / 4) * (i - 1)) }}
                  </text>

                  <!-- X-axis labels -->
                  <text v-for="(point, i) in currentItem.dailyData" :key="`x-label-${i}`"
                    :x="60 + (i * 680 / (currentItem.dailyData.length - 1))" y="285" text-anchor="middle" font-size="10"
                    fill="#6b7280">
                    {{ point.date }}
                  </text>
                </svg>
              </div>
            </div>

            <div class="trend-summary">
              <div class="summary-card">
                <h4>平均日进度</h4>
                <div class="value">{{ avgDaily }}</div>
                <div class="description">每日平均完成量</div>
              </div>
              <!-- <div class="summary-card">
                <h4>条目价值</h4>
                <div class="value">${{ currentItem?.price || 0 }}</div>
                <div class="description">基于完成数量计算</div>
              </div> -->
            </div>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import type { Project, TimelineDataPoint } from '../types'
import { progressApi } from '../api/services/progress'
import { dataService } from '../api/services/data'

interface DailyData {
  date: string
  value: number
  target: number
}

interface TrendItem {
  id: string
  name: string
  type: string
  target: number
  current: number
  price: number
  status: string
  dailyData: DailyData[]
}

const props = defineProps<{
  visible: boolean
  project: Project | null
}>()

const emit = defineEmits<{
  'update:visible': [value: boolean]
}>()

const currentItemIndex = ref(0)
const loading = ref(false)
const error = ref<string | null>(null)
const trendData = ref<TrendItem[]>([])
const projectProgressData = ref<any>(null)
const exportLoading = ref(false)



// 获取类型显示名称
const getTypeDisplayName = (type: string): string => {
  const typeNames: Record<string, string> = {
    'backlinks': '综合外链',
    'pr': 'PR通稿',
    'social': '社交媒体推广',
    'guest_post': '客座文章',
    'directory': '目录提交',
    'forum': '论坛发帖',
    'PR通稿': 'PR通稿',
    '综合外链': '综合外链'
  }
  return typeNames[type] || type
}

// 获取导出类型参数
const getExportSourceType = (type: string): string => {
  const typeMapping: Record<string, string> = {
    'PR通稿': 'PR',
    '综合外链': 'AUTO',
    '高价值外链': 'MANUAL',
    'UGC外链': 'UGC',
    'pr': 'PR',
    'backlinks': 'AUTO'
  }
  return typeMapping[type] || 'AUTO'
}

// 计算类型价格（简化计算，实际应该从合同数据获取）
const calculateTypePrice = (type: string, quantity: number): number => {
  const pricePerUnit: Record<string, number> = {
    'backlinks': 20,
    'pr': 200,
    'social': 15,
    'guest_post': 100,
    'directory': 10,
    'forum': 25,
    'PR通稿': 200,
    '综合外链': 20
  }
  return (pricePerUnit[type] || 10) * quantity
}

// 格式化日期
const formatDate = (dateStr: string): string => {
  const date = new Date(dateStr)
  return `${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 转换时间线数据为趋势数据格式
const convertTimelineToTrendData = (timelineData: any[]): TrendItem[] => {
  if (!Array.isArray(timelineData) || timelineData.length === 0) {
    return []
  }

  const typeMap = new Map<string, TrendItem>()

  // 遍历时间线数据，构建每个类型的趋势数据
  timelineData.forEach((point, index) => {
    if (!point.progress) return

    Object.entries(point.progress).forEach(([typeName, typeData]: [string, any]) => {
      // 过滤掉"金额使用"项
      if (typeName === '金额使用') return

      if (!typeMap.has(typeName)) {
        // 获取该类型的目标数量
        const progressInfo = getRequirementProgress(typeName)
        const targetQuantity = progressInfo.targetQuantity || 0

        typeMap.set(typeName, {
          id: typeName,
          name: getTypeDisplayName(typeName),
          type: typeName,
          target: targetQuantity,
          current: Math.round(typeData.completed_quantity || 0),
          price: calculateTypePrice(typeName, Math.round(typeData.completed_quantity || 0)),
          status: 'ACTIVE',
          dailyData: []
        })
      }

      const trendItem = typeMap.get(typeName)!
      trendItem.dailyData.push({
        date: formatDate(point.date),
        value: Math.round(typeData.completed_quantity || 0),
        target: trendItem.target
      })

      // 更新当前值为最新的完成数量
      if (index === timelineData.length - 1) {
        trendItem.current = Math.round(typeData.completed_quantity || 0)
      }
    })
  })

  return Array.from(typeMap.values())
}

// 获取特定需求类型的进度信息（类似 ProjectRow.vue 中的逻辑）
const getRequirementProgress = (requirementType: string) => {
  if (!projectProgressData.value?.type_progress_data) {
    return { completionRate: 0, completedQuantity: 0, targetQuantity: 0 }
  }

  const typeData = projectProgressData.value.type_progress_data[requirementType]
  if (!typeData) {
    return { completionRate: 0, completedQuantity: 0, targetQuantity: 0 }
  }

  return {
    completionRate: typeData.completion_rate,
    completedQuantity: typeData.completed_quantity,
    targetQuantity: typeData.target_quantity
  }
}

// 获取项目进度数据
const fetchProjectProgressData = async () => {
  if (!props.project?.id) return

  try {
    const result = await progressApi.getProjectProgressSafe(props.project.id)
    if (result.success) {
      projectProgressData.value = result.data
    }
  } catch (error) {
    console.error('Failed to fetch project progress data:', error)
  }
}

// 获取项目时间线数据
const fetchTimelineData = async () => {
  if (!props.project?.id) return

  loading.value = true
  error.value = null

  try {
    console.log('Fetching timeline data for project:', props.project.id)

    // 同时获取进度数据和时间线数据
    await fetchProjectProgressData()

    const result = await progressApi.getProjectTimelineSafe(props.project.id)
    console.log('Timeline result:', result)

    if (result.success && result.data) {
      // 直接使用 result.data，它就是时间线数据数组
      const timelineData = result.data
      console.log('Timeline data:', timelineData)

      // 检查数据是否为数组
      if (Array.isArray(timelineData) && timelineData.length > 0) {
        // 转换API数据为组件需要的格式
        trendData.value = convertTimelineToTrendData(timelineData)
        console.log('Converted trend data:', trendData.value)
      } else {
        error.value = '暂无时间线数据'
      }
    } else {
      error.value = result.error || '获取时间线数据失败'
    }
  } catch (err: any) {
    console.error('Timeline fetch error:', err)
    error.value = err.message || '获取数据时发生错误'
  } finally {
    loading.value = false
  }
}



const currentItem = computed(() => trendData.value[currentItemIndex.value])

const maxValue = computed(() => {
  if (!currentItem.value || currentItem.value.dailyData.length === 0) return 100
  const maxDataValue = Math.max(...currentItem.value.dailyData.map(d => d.value))
  const targetValue = currentItem.value.target || 0
  return Math.max(maxDataValue, targetValue, 10) // 确保包含目标值和最小值10
})

const progress = computed(() => {
  if (!currentItem.value || !currentItem.value.target) return 0
  return Math.round((currentItem.value.current / currentItem.value.target) * 100)
})

const remaining = computed(() => {
  if (!currentItem.value) return 0
  return Math.max(0, currentItem.value.target - currentItem.value.current)
})

const totalDays = computed(() => {
  if (!currentItem.value) return 0
  return currentItem.value.dailyData.length
})

const weeklyChange = computed(() => {
  if (!currentItem.value || currentItem.value.dailyData.length < 8) return 0
  const lastWeekValue = currentItem.value.dailyData[currentItem.value.dailyData.length - 8].value
  return currentItem.value.current - lastWeekValue
})

const avgDaily = computed(() => {
  if (!currentItem.value) return '0.0'
  const avg = currentItem.value.current / currentItem.value.dailyData.length
  return avg.toFixed(1)
})

const progressPath = computed(() => {
  if (!currentItem.value) return ''
  const points = currentItem.value.dailyData.map((d, i) =>
    `${60 + (i * 680 / (currentItem.value!.dailyData.length - 1))} ${260 - (d.value / maxValue.value) * 200}`
  )
  return `M ${points.join(' L ')}`
})

const areaPath = computed(() => {
  if (!currentItem.value) return ''
  const points = currentItem.value.dailyData.map((d, i) =>
    `${60 + (i * 680 / (currentItem.value!.dailyData.length - 1))} ${260 - (d.value / maxValue.value) * 200}`
  )
  return `M 60 260 L ${points.join(' L ')} L 740 260 Z`
})



const switchTab = (index: number) => {
  currentItemIndex.value = index
}

const closeModal = () => {
  emit('update:visible', false)
}

// 导出当前类型的数据
const exportCurrentData = async () => {
  if (!props.project?.id || !currentItem.value || exportLoading.value) {
    return
  }

  exportLoading.value = true

  try {
    const sourceType = getExportSourceType(currentItem.value.type)
    await dataService.exportProjectData(props.project.id, sourceType)

    // 可以添加成功提示
    console.log('数据导出成功')
  } catch (err: any) {
    console.error('导出失败:', err)
    // 可以添加错误提示
    alert('导出失败: ' + (err.message || '未知错误'))
  } finally {
    exportLoading.value = false
  }
}

// 重置到第一个标签页当弹窗打开时，并获取数据
watch(() => props.visible, (newVal) => {
  if (newVal) {
    currentItemIndex.value = 0
    fetchTimelineData()
  }
})
</script>
<style scop ed>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 12px;
  width: 100%;
  max-width: 1000px;
  max-height: 90vh;
  overflow: hidden;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.25);
  animation: modalSlideIn 0.3s ease-out;
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-20px) scale(0.95);
  }

  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.modal-header {
  padding: 24px 30px;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-title h2 {
  font-size: 20px;
  color: #1f2937;
  margin-bottom: 4px;
}

.modal-title p {
  font-size: 14px;
  color: #6b7280;
}

.close-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: #f3f4f6;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.close-btn:hover {
  background: #e5e7eb;
}

.modal-body {
  padding: 0;
  max-height: calc(90vh - 120px);
  overflow-y: auto;
}

.tabs-container {
  border-bottom: 1px solid #e5e7eb;
  background: #f9fafb;
}

.tabs {
  display: flex;
  padding: 0 30px;
  overflow-x: auto;
}

.tab {
  padding: 16px 20px;
  border: none;
  background: none;
  cursor: pointer;
  font-size: 14px;
  color: #6b7280;
  border-bottom: 2px solid transparent;
  transition: all 0.2s;
  white-space: nowrap;
  position: relative;
}

.tab:hover {
  color: #374151;
}

.tab.active {
  color: #6366f1;
  border-bottom-color: #6366f1;
  background: white;
}

.tab-badge {
  background: #e5e7eb;
  color: #6b7280;
  font-size: 11px;
  padding: 2px 6px;
  border-radius: 10px;
  margin-left: 8px;
}

.tab.active .tab-badge {
  background: #e0e7ff;
  color: #6366f1;
}

.chart-container {
  padding: 30px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  gap: 20px;
}

.chart-info {
  flex: 1;
}

.chart-info h3 {
  font-size: 18px;
  color: #1f2937;
  margin-bottom: 4px;
}

.chart-info p {
  font-size: 14px;
  color: #6b7280;
}

.chart-actions {
  display: flex;
  align-items: flex-start;
}

.export-btn {
  padding: 8px 16px;
  background: #6366f1;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 6px;
  min-width: 120px;
  justify-content: center;
}

.export-btn:hover:not(:disabled) {
  background: #4f46e5;
}

.export-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.export-btn.loading {
  background: #6b7280;
}

.export-content,
.export-loading {
  display: flex;
  align-items: center;
  gap: 6px;
}

.export-spinner {
  width: 14px;
  height: 14px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top: 2px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.chart-stats {
  display: flex;
  gap: 24px;
  flex-shrink: 0;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 2px;
}

.stat-label {
  font-size: 12px;
  color: #6b7280;
}

.stat-change {
  font-size: 12px;
  margin-top: 2px;
}

.stat-change.positive {
  color: #10b981;
}

.stat-change.negative {
  color: #ef4444;
}

.chart-wrapper {
  background: #f9fafb;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.chart {
  width: 100%;
  height: 300px;
  position: relative;
  background: white;
  border-radius: 6px;
  border: 1px solid #e5e7eb;
}

.chart-canvas {
  width: 100%;
  height: 100%;
}

.line-path {
  stroke: #6366f1;
  stroke-width: 2;
  fill: none;
}

.line-area {
  fill: url(#gradient);
  opacity: 0.1;
}

.line-point {
  fill: #6366f1;
  stroke: white;
  stroke-width: 2;
  r: 4;
  cursor: pointer;
}

.line-point:hover {
  r: 6;
  fill: #4f46e5;
}

.trend-summary {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-top: 20px;
}

.summary-card {
  background: white;
  padding: 16px;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
}

.summary-card h4 {
  font-size: 14px;
  color: #374151;
  margin-bottom: 8px;
}

.summary-card .value {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

.summary-card .description {
  font-size: 12px;
  color: #6b7280;
  margin-top: 4px;
}

/* Loading, Error, and No Data States */
.loading-container,
.error-container,
.no-data-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #e5e7eb;
  border-top: 3px solid #6366f1;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.loading-container p,
.error-container p,
.no-data-container p {
  color: #6b7280;
  font-size: 14px;
  margin: 0;
}

.error-icon,
.no-data-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.retry-btn {
  margin-top: 16px;
  padding: 8px 16px;
  background: #6366f1;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.2s;
}

.retry-btn:hover {
  background: #4f46e5;
}
</style>